""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                   __         __     __    __                               "
"                  /\ \       /\ \   /\ '-./  \                              "
"                  \ \ \____  \ \ \  \ \ \-./\ \                             "
"                   \ \_____\  \ \_\  \ \_\ \ \_\                            "
"                    \/_____/   \/_/   \/_/  \/_/                            "
"                                                                            "
"                                                                            "
"    This is the personal .vimrc file of Steve Lemuel.                       "
"    While much of it is beneficial for general use, I would                 "
"    recommend picking out the parts you want and understand.                "
"                                                                            "
"    "Copyright 2015 Steve Lemuel <wlemuel@hotmail.com>"                     "
"                                                                            "
"    Licensed under the Apache License, Version 2.0 (the 'License');         "
"    you may not use this file except in compliance with the License.        "
"    You may obtain a copy of the License at                                 "
"                                                                            "
"        http://www.apache.org/licenses/LICENSE-2.0                          "
"                                                                            "
"    Unless required by applicable law or agreed to in writing, software     "
"    distributed under the License is distributed on an 'AS IS' BASIS,       "
"    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or         "
"    implied.                                                                "
"    See the License for the specific language governing permissions and     "
"    limitations under the License.                                          "
"                                                                            "
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" PRE-INIT                                                                   "
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim"
  finish
endif

set shell=/bin/sh

" Don't use Ex mode, use Q for formatting
map Q gq

" CTRL-U in insert mode deletes a lot.  Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>

" In many terminal emulators the mouse works just fine, thus enable it.
"if has('mouse')
  "set mouse=a
"endif

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
  syntax on
  set hlsearch
endif

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" FUNCTIONS                                                                  "
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Judge the current system
fun! Mysys()
    if exists('g:vimrc_os')
        return g:vimrc_os
    else
    if has("win32") || has("win64") || has("win32unix")
        let g:vimrc_os = "win32"
    elseif has("mac")
        let g:vimrc_os = "mac"
    else
        let g:vimrc_os = "unix"
    endif
    return g:vimrc_os
endfun

" Returns true if paste mode is enabled
fun! HasPaste()
    if &paste
        return 'PASTE MODE  '
    en
    return ''
endfun
" Scroll smoothly
function! SmoothScroll(up)
    if a:up
        let scrollaction="^Y"
    else
        let scrollaction="^E"
    endif
    exec "normal " . scrollaction
    redraw
    let counter=1
    while counter<&scroll
        let counter+=1
        sleep 10m
        redraw
        exec "normal " . scrollaction
    endwhile
endfunction

"Active django mode
fun! DjangoMode()
    Bundle 'superSnipMate'
    au FileType python set ft=python.django
    au FileType html set ft=htmldjango.html
    echo "Django Mode Actived successfully!"
endfun

"Strip trailing whitespace
"fun! StripTrailingWhitespace()
"    " Don't strip on this filetype
"    if &ft =! 'markdown'
"        return
"    endif
"    %s/\s\+$//e
"endfun

fun! RemoveWindowsMark()
    %s/^M/\r/g
endfun

"Encoding
fun! ViewUTF8()
    set encoding=utf-8
    set termencoding=big5
endfun

fun! UTF8()
    set encoding=utf-8
    set termencoding=big5
    set fileencoding=utf-8
    set fileencodings=ucs-bom,big5,utf-8,latin1
endfun

fun! Big5()
    set encoding=big5
    set fileencoding=big5
endfun

function! GetBufferList()
  redir =>buflist
  silent! ls!
  redir END
  return buflist
endfunction

function! ToggleList(bufname, pfx)
    let buflist = GetBufferList()
    for bufnum in map(filter(split(buflist, '\n'), \
        'v:val =~ "'.a:bufname.'"'), 'str2nr(matchstr(v:val, "\\d\\+"))')
        if bufwinnr(bufnum) != -1
            exec(a:pfx.'close')
            return
        endif
    endfor
    if a:pfx == 'l' && len(getloclist(0)) == 0
        echohl ErrorMsg
        echo "Location List is Empty."
        return
    endif
    let winnr = winnr()
    exec(a:pfx.'open')
    if winnr() != winnr
        wincmd p
    endif
endfunction

"Run the gdb with the current file.
func! Rungdb()
	exec "w"
	exec "!g++ % -g -o %<"
	exec "!gdb ./%<"
endfunc

"Compile the current file.
func! CompileRunGcc()
	exec "w"
	if &filetype == 'c'
		exec "!g++ % -o %<"
		exec "!time ./%<"
	elseif &filetype == 'cpp'
		exec "!g++ % -o %<"
		exec "!time ./%<"
	elseif &filetype == 'java'
		exec "!javac %"
		exec "!time java %<"
	elseif &filetype == 'sh'
		:!time bash %
	elseif &filetype == 'python'
		exec "!time python %"
    "elseif &filetype == 'html'
        "exec "!firefox % &"
    elseif &filetype == 'go'
"        exec "!go build %<"
        exec "!time go run %"
    elseif &filetype == 'mkd'
        exec "!~/.vim/utils/markdown.pl % > %.html &"
        "exec "!firefox %.html &"
	endif
endfunc

"Format current file.
func FormartSrc()
    exec "w"
    if &filetype == 'c'
        exec "!astyle --style=ansi -a --suffix=none %"
    elseif &filetype == 'cpp' || &filetype == 'hpp'
        exec "r !astyle --style=ansi --one-line=keep-statements -a --suffix=none %> /dev/null 2>&1"
    elseif &filetype == 'perl'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'py'||&filetype == 'python'
        exec "r !autopep8 -i --aggressive %"
    elseif &filetype == 'java'
        exec "!astyle --style=java --suffix=none %"
    elseif &filetype == 'jsp'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'xml'
        exec "!astyle --style=gnu --suffix=none %"
    else
        exec "normal gg=G"
        return
    endif
    exec "e! %"
endfunc


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"  Vundle Loading                                                           "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Vundle{
"set nocompatible
"filetype off
"
"let g:hasVundle = 0
"let s:VundleDir = $HOME . '/.vim/bundle/Vundle.vim'
"if isdirectory(s:VundleDir)
"    let g:hasVundle = 1
"else
"    try
"        !git clone https://github.com/gmarik/Vundle.vim ~/.vim/bundle/Vundle.vim
"        let g:hasVundle = 1
"    catch
"        let g:hasVundle = 0
"    endtry
"
"endif
"
"if g:hasVundle == 1
"if Mysys() == 'win32'
"    let $LANG = 'en'  "set message language
"    set langmenu=en   "set menu's language of gvim. no spaces beside '='
"    set rtp+=$HOME/.vim/bundle/Vundle.vim/
"    call vundle#rc()
"else
"    set rtp+=$HOME/.vim/bundle/Vundle.vim/
"    call vundle#rc()
"endif
"
"Bundle 'gmarik/Vundle.vim'
"}
call plug#begin('~/.vim/bundle')

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"  PLUGINS                                                                  "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"vim-scripts-repos{
"common{
Plug 'hecal3/vim-leader-guide'
Plug 'ctjhoa/spacevim'
"Plug 'taglist.vim'
"Plug 'cscope.vim'
Plug 'StripWhiteSpaces'
Plug 'mhinz/vim-startify'
if has('gui_running')
    Plug 'readnovel'
endif
Plug 'itchyny/calendar.vim'
Plug 'The-NERD-Commenter'
Plug 'The-NERD-tree'
"Plug 'Projmgr'
Plug 'sessionman.vim'
Plug 'bufexplorer.zip'
Plug 'fholgado/minibufexpl.vim'
"Plug 'mru.vim'
Plug 'EasyMotion'
Plug 'tpope/vim-surround'
Plug 'Shougo/unite.vim'
"Plug 'superSnipMate'
"Plug 'better-snipmate-snippet'
"Plug 'Ultisnips'
Plug 'ervandew/supertab'
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'
Plug 'wlemuel/AuthorInfo'
Plug 'winmanager'
Plug 'gregsexton/gitv'
"Plug "Raimondi/delimitMate"
Plug 'howiefh/vimcdoc'
Plug 'wakatime/vim-wakatime'

if Mysys() != 'win32'
"Plug 'Lokaltog/powerline'
Plug 'bling/vim-airline'
Plug 'paranoida/vim-airlineish'
Plug 'Yggdroot/indentLine'
Plug 'Valloric/YouCompleteMe', {'do': './install.py'}
Plug 'vim-do'
Plug 'benmills/vimux'
endif

"Plug 'Shougo/neocomplcache'
"Plug 'garbas/vim-snipmate'
"Plug 'closetag.vim'
"Plug 'vim-flake8'
Plug 'grep.vim'
Plug 'multiAPIsyntax'
"Plug 'vimtips.zip'
"Plug 'lrc.vim'
"Plug 'vim-kickstart'
"Plug 'log.vim'
"Plug 'prop.vim'
Plug 'syntaxdosini.vim'
"Plug 'sql.vim'
"Plug 'easytags.vim'
"Plug 'wesnothcfg.vim'
Plug 'timestamp.vim'
Plug 'comments.vim'
"Plug 'scrooloose/syntastic'
Plug 'DoxygenToolkit.vim'
Plug 'xolox/vim-misc'
"Plug 'xolox/vim-easytags'
Plug 'xolox/vim-notes'
"Plug 'wlemuel/qiushibaike'
Plug 'fidian/hexmode'
"Plug 'jistr/vim-nerdtree-tabs'
Plug 'low-ghost/nerdtree-fugitive'
Plug 'majutsushi/tagbar'
Plug 'terryma/vim-multiple-cursors'
Plug 'wlemuel/ToggleNERDTreeAndTagbar'
if Mysys() != 'win32'
    Plug 'yonchu/accelerated-smooth-scroll'
    Plug 'ianva/vim-youdao-translater'
endif
Plug 'markwu/manpageview'
Plug 'tpope/vim-fugitive'
Plug 'tomasr/molokai'
Plug 'mbbill/undotree'
Plug 'kien/ctrlp.vim'
Plug 'ctrlp-modified.vim'
Plug 'tacahiroy/ctrlp-funky'
Plug 'newclear/vim-pyclewn'
Plug 'godlygeek/tabular'
Plug 'tpope/vim-repeat'
Plug 'rking/ag.vim'
Plug 'ctrlsf.vim'
Plug 'sjl/gundo.vim'
Plug 'flazz/vim-colorschemes'
Plug 'supersearch'
Plug 'lucc/vim-tip'
Plug 'vim-auto-save'
"Plug 'vimfortune'
Plug 'ywgx/auto.vim'
Plug 'dag/vim-fish'
Plug 'SQLComplete.vim'
Plug 'vim-orgmode'
Plug 'speeddating.vim'
Plug 'narrow_region'
Plug 'metakirby5/codi.vim'
"}

"flex{
"Plug 'Flex-4'
"}

"actionscript{
"Plug 'actionscript.vim'
"}

"elm{
Plug 'lambdatoast/elm.vim'
"}

"javascript{
"Plug 'Enhanced-JavaScript-syntax'
"Plug 'JavaScript-syntax'
"Plug 'JQuery'
"Plug 'mxw/vim-jsx'
"Plug 'jsx/jsx.vim'
"Plug 'ternjs/tern_for_vim'
"Plug 'pangloss/vim-javascript'
"Plug 'cuzzo/react-complete-me'
"Plug 'cuzzo/react-complete-me'
"Plug 'pangloss/vim-javascript'
"Plug 'jelera/vim-javascript-syntax'
Plug 'alexbyk/vim-ultisnips-react'
Plug 'wlemuel/vim-ultisnips-redux'
Plug 'isRuslan/vim-es6'
"Plug 'othree/yajs.vim'
Plug 'maksimr/vim-jsbeautify'
Plug 'einars/js-beautify'
"}

if &ft =~ 'sh'
"bash{
"Plug 'bash-support.vim'
"}
endif

"perl{
"Plug 'perl-support.vim'
"}

"haskell{
"Plug 'lukerandall/haskellmode-vim'
Plug 'neovimhaskell/haskell-vim'
"}

"cpp{
Plug 'Chiel92/vim-autoformat'
Plug 'wlemuel/a.vim'
"Plug 'vim-cpp-auto-include'
"Plug 'echofunc.vim'
"Plug 'OmniCppComplete'
Plug 'gtk-vim-syntax'
"Plug 'clang-complete'
Plug 'SDL-library-syntax-for-C'
"Plug 'opengl.vim'
Plug 'rhysd/vim-clang-format'
let g:cpp_mode_enabled = 1
"}

if &ft =~ 'markdown' || &ft =~ 'vundle'
"markdown{
"Plug 'Markdown'
"Plug 'Markdown-syntax'
Plug 'plasticboy/vim-markdown'
"}
endif

if &ft =~ 'css' || &ft =~ 'vundle'
"css{
"Plug 'css_color.vim'
"Plug 'css3-syntax-plus'
Plug 'less-syntax'
Plug 'Better-CSS-Synax-for-vim'
Plug 'tpope/vim-haml'
"}
endif

"html{
"Plug 'vim-htmldjango_omnicomplete'
"Plug 'html_FileCompletion'
"Plug 'HTML-AutoCloseTag'
"Plug 'othree/html5.vim'
"Plug 'InfoGeeker/html5.vim' "better
Plug 'mattn/emmet-vim'
"}

"Color Schemes{
Plug 'rickharris/vim-blackboard'
Plug 'altercation/vim-colors-solarized'
Plug 'rickharris/vim-monokai'
Plug 'tpope/vim-vividchalk'
Plug 'Lokaltog/vim-distinguished'
Plug 'chriskempson/vim-tomorrow-theme'
Plug 'fisadev/fisa-vim-colorscheme'
"}

"cmake{
"Plug 'cmake.vim'
"}

if &ft =~ 'python' || &ft =~ 'vundle'
"Python{
"Plug 'PyChimp'
"Plug 'pygtk_syntax'
"Plug 'klen/python-mode'
"Plug 'VimPdb'
Plug 'python_ifold'
Plug 'indentpython.vim'
"Plug 'SuperTab'
"Plug 'python_import.vim'
"Plug 'pythoncomplete'
"Plug 'compilerpython.vim'
"Plug 'pydoc.vim'
"Plug 'pylint.vim'
"Plug 'Pydiction'
"Plug 'python.vim'
"Plug 'pythonhelper'
"Plug 'davidhalter/jedi-vim'
let g:python_mode_enabled = 1
"}
endif

"Go{
Plug 'fatih/vim-go'
"}

"swift{
Plug 'keith/swift.vim'
"}

"nim{
Plug 'zah/nim.vim'
"}

"writing{
"Plug 'junegunn/goyo.vim'
"Plug 'junegunn/limelight.vim'
"}

"Other_Tools{
Plug 'rygwdn/vim-conque'
Plug 'vim-scripts/DrawIt'
"Plug 'vim-scripts/sketch.vim'
"}

"Game{
"Plug 'vim-scripts/TeTrIs.vim'
"Plug 'uguu-org/vim-matrix-screensaver'
"Plug 'adelarsq/Snake.vim'
"Plug 'vim-scripts/Nibble'
"Plug 'satanson/VIMgo2048'
"Plug 'clones/vim-genutils'
"Plug 'Tower-of-Hanoi'
Plug 'mattn/invader-vim'
"}

call plug#end()
"endif


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" CONFIGURATION                                                             "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Global Configure{

"Show line number
set nu

"Set background to dark when running in console
if !has("gui_running")
    set background=dark
endif

if has("gui_running")
    colorscheme molokai
endif

set modelines=0
if Mysys() != 'win32'
    set t_Co=256
    set term=xterm-256color
endif

set nocompatible

set backspace=indent,eol,start

"Keep 100 lines of command line history
set history=100

"Show the cursor position all the time
set ruler

"Display incomplete commands
set showcmd

"Do incremental searching
set incsearch
set confirm
set nowrap

"Set the file encoding
set encoding=utf-8
set fileencodings=utf-8,ucs-bom,iso-2022-jp-3,iso-2022-jp,eucjp-ms,euc-jisx0213,euc-jp,sjis,cp932,gbk
set sessionoptions+=unix,slash

"Detect file type
filetype on
filetype plugin on
filetype indent on

"Disable the swap and backup
"set nobackup
"set noswapfile

set viminfo+=!

set splitright

"Show matching bracet
set showmatch
set wildmenu

"Backspace and cursor keys wrap to
set whichwrap+=<,>,h,l

set report=0

"Ignore case when searching
set ignorecase
set smartcase
set incsearch
set hlsearch

"Set magic on
set magic

"No sound on errors
set noerrorbells
set novisualbell
set t_vb=

set autoindent

"Set indent with 4 spaces replace tab
set softtabstop=4
set expandtab
set sw=4
set ts=4

"Highlight the current line.
"set cul
autocmd FileType javascript,python setlocal cul
autocmd InsertLeave *.js,*.html,*.py se nocul
autocmd InsertEnter *.js,*.html,*.py se cul

"Show the input command
set showcmd

"Set cmd height
set cmdheight=1

"Save the global variables.
set viminfo+=!

"Set help language en(default), zh(Chinese)
set helplang=en

" Don't redraw while executing macros (good performance config)
set lazyredraw

"Set to auto read when a file is changed from the outside
if exists("&autoread")
    set autoread
endif

"Have the mouse enabled all the time:
" set mouse=a

"Make the file be autoload after modified.
set autoread

"Share the clipboard to the system
"set clipboard+=unnamed

"Set mapleader
let mapleader=" "
let g:mapleader=" "
"let g:leaderGuide_vertical = 1

"Using tab with makefile or tags
au FileType make,tags,tag set noexpandtab
au FileType Makefile set noexpandtab

"Strip trailing whitespace for all the files
"au BufWritePre * call StripTrailingWhitespace()

"Remove windows mark like ^M
"au BufWritePre * call RemoveWindowsMark()
"au BufReadPost * call RemoveWindowsMark()

" Only do this part when compiled with support for autocommands.
if has("autocmd")
    filetype plugin indent on

    " For all text files set 'textwidth' to 78 characters.
    autocmd FileType text setlocal textwidth=78

    " Return to last edit position when opening files (You want this!)
    autocmd BufReadPost *
        \ if line("'\"") > 1 && line("'\"") <= line("$") |
        \   exe "normal! g`\"" |
        \ endif
else
    set autoindent		" always set autoindenting on
endif

if !exists(":DiffOrig")
  command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
		  \ | wincmd p | diffthis
endif

"Define some global vimrc variables
if Mysys() == 'win32'
    let g:vimrc_data_path = ''
else
    let g:vimrc_data_path = '$HOME/.vim/data'
endif

if &ft == "tags"
    set tags=$HOME/.vim/config/tags
endif

"for js, html and css
autocmd FileType javascript setlocal ts=2
autocmd FileType javascript setlocal sw=2
autocmd FileType javascript setlocal softtabstop=2
autocmd FileType html,css setlocal ts=2
autocmd FileType html,css setlocal sw=2
autocmd FileType html,css setlocal softtabstop=2

"for nas
autocmd BufReadPost *.nas set ft=asm

"to add dict for different programming language.
au FileType php setlocal dict+=~/.vim/data/dict/php_funclist.dict
au FileType css setlocal dict+=~/.vim/data/dict/css.dict
au FileType c setlocal dict+=~/.vim/data/dict/c.dict
au FileType cpp setlocal dict+=~/.vim/data/dict/cpp.dict
au FileType scale setlocal dict+=~/.vim/data/dict/scale.dict
au FileType javascript setlocal dict+=~/.vim/data/dict/javascript.dict
au FileType html setlocal dict+=~/.vim/data/dict/javascript.dict
au FileType html setlocal dict+=~/.vim/data/dict/css.dict

"close the NERDTree when only it exists.
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" PLUGIN CONFIGURATION                                                      "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"---------------------------------------------------------
" spacevim [active]
"---------------------------------------------------------
let g:dotspacevim_configuration_layers = ['core/.*', 'git', 'syntax-checking']
let g:dotspacevim_additional_plugins = ['ctjhoa/miro7']
"let g:dotspacevim_excluded_plugins = ['haya14busa/incsearch.vim']



"---------------------------------------------------------
" startify [active]
"---------------------------------------------------------
let g:startify_change_to_dir = 1
let g:startify_session_dir = '~/.vim/sessions'
let g:startify_bookmark_dir = '~/.vim/backup/NerdBookmarks.txt'
let g:startify_bookmarks = [
    \ {'c': '~/.vimrc'},
    \ {'p': '~/.vim/config/python.vimrc'},
    \ ]
"let g:startify_commands = [
    "\ ['Vim Reference', 'h ref'],
    "\ {'m': ['My magical function', 'call Magic()']},
    "\ ]
let g:startify_commands = [
    \ {'i': ['Install Plugins', 'PlugInstall']},
    \ {'u': ['Update Plugins',  'PlugUpdate']}
    \ ]
let g:startify_list_order = [
        \ ['   My most recently used files:'],
        \ 'files',
        \ ['   Sessions:'],
        \ 'sessions',
        \ ['   Bookmarks:'],
        \ 'bookmarks',
        \ ['   Commands:'],
        \ 'commands',
        \ ]
let g:startify_custom_header = [
        \ '        __         __     __    __          ',
        \ '       /\ \       /\ \   /\ `-./  \         ',
        \ '       \ \ \____  \ \ \  \ \ \-./\ \        ',
        \ '        \ \_____\  \ \_\  \ \_\ \ \_\       ',
        \ '         \/_____/   \/_/   \/_/  \/_/       ',
        \ '                                            ',
        \ '                      By Steve Lemuel       ',
        \ '       *\(^_^)/*              (v1.01)       ',
        \ '                                            ',
        \ ]

"if Mysys() != 'win32'
    "let g:startify_custom_footer =
      "\ map(split(system('fortune | cowsay'), '\n'),
    "\ '"   ". v:val') + ['','']
"endif

"---------------------------------------------------------
" StripWhiteSpaces [active]
"---------------------------------------------------------
let g:strip_trailing_lines = 1

"---------------------------------------------------------
" calendar.vim [active]
"---------------------------------------------------------
let g:calendar_cache_directory = expand(g:vimrc_data_path.'/calendar.vim/')

"---------------------------------------------------------
" The-NERD-tree [active]
"---------------------------------------------------------
let NERDTreeIgnore = ['.*\.o$','.*\.ko$','.*\.gz$','.*\.pyc$','.*\.so$'.'*\.swp$']
let NERDTreeShowBookmarks=1
let NERDTreeHighlightCursorline=1
let NERDTreeBookmarksFile=g:vimrc_data_path.'/NERDTree/NerdBookmarks.txt'
let NERDChristmasTree=1
let NERDTreeShowLineNumbers=1
let NERDTreeWinPos='right'
nmap <silent> <leader><F9> :NERDTreeToggle<CR>
nmap <silent> <leader>l :NERDTreeToggle<CR>

"---------------------------------------------------------
" sessionman [active]
"---------------------------------------------------------
nmap <silent> <leader>S :SessionList<CR>

"---------------------------------------------------------
" minibufexpl [active]
"---------------------------------------------------------
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplModSelTarget = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplorerAutoStart = 0
map <Leader>mbo :MBEOpen<cr>
map <Leader>mbc :MBEClose<cr>
map <Leader>mbt :MBEToggle<cr>
map <silent> mp :MBEbp<cr>
map <silent> mn :MBEbn<cr>


"---------------------------------------------------------
" EasyMotion [active]
"---------------------------------------------------------
let g:EasyMotion_leader_key = '<leader>e'

"---------------------------------------------------------
" UltiSnips [active]
"---------------------------------------------------------
let g:UltiSnipsSnippetDirectories=['UltiSnips']
let g:UltiSnipsExpandTrigger='<Tab>'
let g:UltiSnipsListSnippets='<S-Tab>'
let g:UltiSnipsJumpForwardTrigger='<C-j>'
let g:UltiSnipsJumpBackwardTriggr='<C-k>'
let g:UltiSnipsSnippetsDir = '~/.vim/data/UltiSnips'


"---------------------------------------------------------
" grep.vim [active]
"---------------------------------------------------------
nnoremap <silent> <leader><F3> :Grep<CR>

"---------------------------------------------------------
" vim-wakatime [active]
"---------------------------------------------------------
let g:wakatime_PythonBinary = '/usr/local/bin/python'

"---------------------------------------------------------
" AuthorInfo [active]
"---------------------------------------------------------
let g:authorInfo_author='Steve Lemuel'
let g:authorInfo_email='wlemuel@hotmail.com'
let g:authorInfo_timeformat='%Y-%m-%d %H:%M:%S'
"let g:authorInfo_license='LGPL'
nmap <leader>r :AuthorInfoDetect<CR>

" SetTitle，add the below content to the start when create new file.
let timestamp_regexp = '\v\C%(<Last %([cC]hanged?|[Mm]odified):\s+)@<=.*$'
let g:timestamp_rep = "%Y-%m-%d %H:%M:%S"

"Auto add Author for the files
au BufNewFile *.py,*.cpp,*.sh,*.java,*.c,*.rb AuthorInfoDetect
au BufWritePre,FileWritePre *.py,*.cpp,*.sh,*.java,*.c,*.pas,*.rb,*.css,*.html AuthorInfoAutoUpdate


"---------------------------------------------------------
" winmanager [active]
"---------------------------------------------------------
"let g:winManagerWindowLayout = "BufExplorer, NERDTree|TagList"
"let g:winManagerWindowLayout = "TagList|NERDTree, BufExplorer"
"let g:winManagerWindowLayout = "NERDTree|TagList, BufExplorer"
"let g:winManagerWidth = 30
"nmap wm :WMToggle<CR>


"---------------------------------------------------------
" vim-fugitive [active]
"---------------------------------------------------------

"---------------------------------------------------------
" ctrlp [active]
"---------------------------------------------------------
set wildignore+=*/tmp/*,*.so,*.swp,*.zip,*.pyc,*.png,*.jpg,*.gif     " MacOSX/Linux
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'
let g:ctrlp_custom_ignore = '\v\.(exe|so|dll)$'
let g:ctrlp_extensions = ['funky']

"---------------------------------------------------------
" undotree [active]
"---------------------------------------------------------
nnoremap <leader>u :UndotreeToggle<CR>
if has("persistent_undo")
    set undodir=g:vimrc_data_path.'/.undodir/'
    set undofile
endif

"---------------------------------------------------------
" ctags
"---------------------------------------------------------
if Mysys() == 'unix'
    let g:tagbar_ctags_bin='$HOME/.bin/ctags'
elseif Mysys() == 'mac'
    let g:tagbar_ctags_bin='/usr/local/bin/ctags'
endif
"let Tlist_Sort_Type = "name"
"let Tlist_Use_Right_Window = 0
"let Tlist_Compart_Format = 1
"let Tlist_Exist_OnlyWindow = 1
"let Tlist_File_Fold_Auto_Close = 0

"set tags+=~/.vim/tags/cpp
"set tags+=~/.vim/tags/gl
"set tags+=~/.vim/tags/sdl
"set tags+=~/.vim/tags/qt4
"set tags+=~/.vim/tags/gtk2
"set tags+=~/.vim/tags/gtk3
"map <C-F12> :!ctags -R --sort=yes --c++-kinds=+p --fields=+iaS --extra=+q .<CR>


"---------------------------------------------------------
" vim-notes [active]
"---------------------------------------------------------
let g:notes_directories = [g:vimrc_data_path.'/notes']
let g:notes_suffix = '.md'

"---------------------------------------------------------
" vim-jsx [active]
"---------------------------------------------------------
let g:jsx_ext_required = 0  "Allow JSX in normal JS files"

"---------------------------------------------------------
" Gundo [active]
"---------------------------------------------------------
try
    set undodir=~/.vim/data/undodir
    set undofile
    nnoremap <leader>gu :GundoToggle<CR>
catch
endtry

"---------------------------------------------------------
" vim-youdao-translator [active]
"---------------------------------------------------------
noremap <leader>yd :Yde<CR>
nnoremap <silent> <C-T> <ESC>:Ydc<CR>
vnoremap <silent> <C-T> <ESC>:Ydv<CR>

"---------------------------------------------------------
" vim-auto-save [active]
"---------------------------------------------------------
let g:auto_save_no_updatetime = 1  " do not change the 'updatetime' option
let g:auto_save_in_insert_mode = 0  " do not save while in insert mode
"let g:auto_save_silent = 1  " do not display the auto-save notification


"---------------------------------------------------------
" vim-jsbeautify [active]
"---------------------------------------------------------
nnoremap <silent> <leader>js :call JsxBeautify()<CR>
"au BufWritePre,FileWritePre *.py,*.cpp,*.sh,*.java,*.c,*.pas,*.rb,*.css,*.html AuthorInfoDetect
"au BufWritePre *.js,*.jsx call JsxBeautify()

"---------------------------------------------------------
" vim-jsx [active]
"---------------------------------------------------------
let g:jsbeautify_file = fnameescape(fnamemodify(expand("<sfile>"), ":h")."/bundle/js-beautify/beautify.js")
"autocmd BufWritePost *.js call JsBeautify()
autocmd FileType javascript,jsx vnoremap <buffer>  <leader>F :call JsBeautify()<cr>

"---------------------------------------------------------
" vim-autoformat [active]
"---------------------------------------------------------
if exists('g:cpp_mode_enabled') && g:cpp_mode_enabled =~ 1
    noremap <leader><F5> :Autoformat<CR><CR>
endif
"}

"---------------------------------------------------------
" indentLine [active]
"---------------------------------------------------------
if Mysys() == 'win32' || &ft == 'help'
    let g:indentLine_enabled = 0
else
    let g:indentLine_enabled = 0
endif


"---------------------------------------------------------
" Youcompleteme [active]
"---------------------------------------------------------
let g:ycm_filetype_blacklist = {
    \   'tagbar' : 1,
    \   'qf' : 1,
    \   'notes' : 1,
    \   'asm' : 1,
    \   'markdown' : 1,
    \   'unite' : 1,
    \   'text'  : 1,
    \   'vimwiki'   : 1,
    \   'pandoc'    : 1,
    \   'infolog'   : 1,
    \   'mail'  :   1
    \}
let g:ycm_key_list_select_completion=['<C-n>','<Down>']
let g:ycm_key_list_previous_completion=['<C-p>','<Up>']
let g:ycm_global_ycm_extra_conf = '~/.vim/data/ycm/ycm_extra_conf.py'
let g:ycm_autoclose_preview_window_after_completion=1

" Add the virtualenv's site-packages to vim path
"if has('python')
"py << EOF
"import os.path
"import sys
"import vim
"if 'VIRTUAL_ENV' in os.environ:
"    project_base_dir = os.environ['VIRTUAL_ENV']
"    sys.path.insert(0, os.path.join(project_base_dir, 'lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'))
"EOF
"endif

"auto close scrach preview window after auto-complete
"autocmd CompleteDone * pclose

"---------------------------------------------------------
" vimux [active]
"---------------------------------------------------------
autocmd Filetype tex nnoremap <buffer> <Leader>rr :update<Bar>:call VimuxRunCommandInDir('latexmk -pdf', 1)<CR>
nmap <Leader>vl :VimuxRunLastCommand<CR>
nmap <Leader>vp :VimuxPromptCommand<CR>
nmap <Leader>vi :VimuxInspectRunner<CR>
nmap <Leader>vq :VimuxCloseRunner<CR>
nmap <Leader>vs :VimuxInterruptRunner<CR>
nmap <Leader>vc :VimuxClearRunnerHistory<CR>
nmap <Leader>vz :call VimuxZoomRunner()<CR>
nmap <Leader>vx :VimuxInterruptRunner<CR>
"nmap <Leader>vm :VimuxPromptCommand("make ")<CR>

"let g:VimuxOrientation = "h"

"---------------------------------------------------------
" DoxygenToolkit [active]
"---------------------------------------------------------
let g:DoxygenToolkit_briefTag_pre="@Synopsis  "
let g:DoxygenToolkit_paramTag_pre="@Param "
let g:DoxygenToolkit_returnTag="@Returns   "
let g:DoxygenToolkit_blockHeader="--------------------------------------------------------------------------"
let g:DoxygenToolkit_blockFooter="----------------------------------------------------------------------------"
let g:DoxygenToolkit_authorName="Steve Lemuel"
"let g:DoxygenToolkit_licenseTag="My own license"   <-- !!! Does not end with "\<enter>"

"---------------------------------------------------------
" tagbar [active]
"---------------------------------------------------------
nmap <silent> <leader>wm :ToggleNERDTreeAndTagbar<CR>
nmap <silent> <leader><F8> :ToggleNERDTreeAndTagbar<CR>
nmap <silent> <leader><F7> :TagbarToggle<CR>
nmap <silent> <leader>h :TagbarToggle<CR>
let g:tagbar_left = 1
let g:tagbar_width=30
let g:tagbar_autoshowtag=0
let g:tagbar_iconchars = ['+', '-']
let w:jumpbacktohere = 1
"let g:tagbar_autofocus = 1

"---------------------------------------------------------
" cscope.vim [active]
"---------------------------------------------------------
"set cscopequickfix=s-,c-,d-,i-,t-,e-
"nmap <C-_>s :cs find s <C-R>=expand("<cword>")<CR><CR>
"nmap <C-_>g :cs find g <C-R>=expand("<cword>")<CR><CR>
"nmap <C-_>c :cs find c <C-R>=expand("<cword>")<CR><CR>
"nmap <C-_>t :cs find t <C-R>=expand("<cword>")<CR><CR>
"nmap <C-_>e :cs find e <C-R>=expand("<cword>")<CR><CR>
"nmap <C-_>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
"nmap <C-_>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
"nmap <C-_>d :cs find d <C-R>=expand("<cword>")<CR><CR>

"---------------------------------------------------------
" syntastic [active]
"---------------------------------------------------------
let g:syntastic_ignore_files=[".*\.py$"]

"---------------------------------------------------------
" a.vim [active]
"---------------------------------------------------------
if exists('g:cpp_mode_enabled') && g:cpp_mode_enabled =~ 1
    nmap <leader><F4> :A<CR>
endif

"---------------------------------------------------------
" Pydiction [active]
"---------------------------------------------------------
if exists('g:python_mode_enabled') && g:python_mode_enabled =~ 1
    let g:pydiction_location = '$HOME/.vim/bundle/Pydiction/complete-dict'
    let g:pydiction_menu_height = 20
endif

"---------------------------------------------------------
" pythoncomplete [active]
"---------------------------------------------------------
au FileType python setlocal omnifunc=pythoncomplete#Complete

"---------------------------------------------------------
" python-mode [active]
"---------------------------------------------------------
let g:pymode_rope_completion = 1
let g:pymode_rope_complete_on_dot = 0
let g:pymode_rope_completion_bind = '<S-Space>'
let g:pymode_rope_autoimport = 1
let g:pymode_lint_on_write = 1
let g:pymode_lint_ignore = "E401,W"
let g:pymode_lint_checkers = ['pyflakes', 'pep8', 'mccabe']

"---------------------------------------------------------
" vim-conque [active]
"---------------------------------------------------------
"ConqueTermTab ConqueTermSplit ConqueTermVSplit
"ConqueTerm bash
"ConqueTerm PowerShell.exe
let g:ConqueTerm_FastMode = 1
let g:ConqueTerm_PromptRegex = '^\w\+@[0-9A-Za-z_.-]\+:[0-9A-Za-z_./\~,:-]\+\$'

"---------------------------------------------------------
" DrawIt [active]
"---------------------------------------------------------
set virtualedit+=block

"---------------------------------------------------------
" vim-airline [active]
"---------------------------------------------------------
if !(Mysys() =~ 'win32')
"set guifont=DejaVu\ Sans\ Mono\ for\ Powerline\ 10
let g:airline#extensions#tabline#enabled = 1
let g:airline_theme="airlineish"
set laststatus=2
let g:airline_powerline_fonts = 1
if !exists('g:airline_symbols')
   let g:airline_symbols = {}
endif

" unicode symbols
"let g:airline_left_sep = '»'
"let g:airline_left_sep = '▶'
"let g:airline_right_sep = '«'
"let g:airline_right_sep = '◀'
"let g:airline_symbols.linenr = '␊'
"let g:airline_symbols.linenr = '␤'
"let g:airline_symbols.linenr = '¶'
"let g:airline_symbols.branch = '⎇'
"let g:airline_symbols.paste = 'ρ'
"let g:airline_symbols.paste = 'Þ'
"let g:airline_symbols.paste = '∥'
"let g:airline_symbols.whitespace = 'Ξ'
"let g:Powerline_mode_V="V·LINE"
"let g:Powerline_mode_cv="V·BLOCK"
"let g:Powerline_mode_S="S·LINE"
"let g:Powerline_mode_cs="S·BLOCK"
endif

"---------------------------------------------------------
" neocompl [active]
"---------------------------------------------------------
"let g:neocomplcache_enable_at_startup = 1
"let g:neocomplcache_enable_smart_case = 1
"let g:neocomplcache_enable_camel_case_completion = 1
"let g:neocomplcache_enable_underbar_completion = 1
"let g:neocomplcache_min_syntax_length = 3
"let g:neocomplcache_lock_buffer_name_pattern = '\*ku\*'
"if !exists('g:neocomplcache_keyword_patterns')
	"let g:neocomplcache_keyword_patterns = {}
"endif
"let g:neocomplcache_keyword_patterns['default'] = '\h\w*'
"imap <C-k>     <Plug>(neocomplcache_snippets_expand)
"smap <C-k>     <Plug>(neocomplcache_snippets_expand)
"inoremap <expr><C-g>     neocomplcache#undo_completion()
"inoremap <expr><C-l>     neocomplcache#complete_common_string()
"inoremap <expr><CR>  neocomplcache#smart_close_popup() . "\<CR>"
"inoremap <expr><C-h> neocomplcache#smart_close_popup()."\<C-h>"
"inoremap <expr><BS> neocomplcache#smart_close_popup()."\<C-h>"
"inoremap <expr><C-Y>  neocomplcache#close_popup()
"inoremap <expr><C-e>  neocomplcache#cancel_popup()
"inoremap <expr><Enter>  pumvisible() ? "\<C-Y>" : "\<Enter>"
"let g:neocomplcache_enable_auto_select = 1

"autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
"autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
"autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
"autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags

"if !exists('g:neocomplcache_omni_patterns')
	"let g:neocomplcache_omni_patterns = {}
"endif
"}

"---------------------------------------------------------
" supertab [active]
"---------------------------------------------------------
let g:SuperTabDefaultCompletionType='<C-n>'


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" KEYMAPS                                                                   "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Command | Normal | Visual | Operator-Pending | Insert-only | Command-line "
"---------+--------+--------+------------------+-------------+--------------"
"  :map   | ###### | ###### | ################ |             |              "
"---------+--------+--------+------------------+-------------+--------------"
"  :nmap  | ###### |        |                  |             |              "
"---------+--------+--------+------------------+-------------+--------------"
"  :vmap  |        | ###### |                  |             |              "
"---------+--------+--------+------------------+-------------+--------------"
"  :omap  |        |        | ################ |             |              "
"---------+--------+--------+------------------+-------------+--------------"
"  :map!  |        |        |                  | ########### | ############ "
"---------+--------+--------+------------------+-------------+--------------"
"  :imap  |        |        |                  | ########### |              "
"---------+--------+--------+------------------+-------------+--------------"
"  :cmap  |        |        |                  |             | ############ "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
nmap cS :%s/\s\+$//g<CR>:noh<CR>
nmap cM :%s/\r$//g<CR>:noh<CR>

"Bash like keys for the command line
cnoremap <C-A> <Home>
cnoremap <C-E> <End>
cnoremap <C-K> <C-U>

" Switch CWD to the directory of the open buffer
nnoremap <leader>cd :cd %:p:h<CR>:pwd<CR>

" Opens a new tab with the current buffer's path
" Super useful when editing files in the same directory
"nmap <silent> <leader>te :tabedit <c-r>=expand("%:p:h")<cr>/

"Fast saving
nnoremap <leader>w :w!<CR>

"Fast quit
nnoremap <silent> <leader>q :qa<CR>

"Fast safe quit
nnoremap <silent> <leader>x :xa<CR>

"Treat long lines as break lines (useful when moving around in them)
nmap j gj
nmap k gk

"Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l

"Smart way to move in the insert mode
"Show keys in insert mode with 'help ins-special-keys'
inoremap <C-j> <Down>
inoremap <C-k> <Up>
inoremap <C-a> <Home>
inoremap <C-e> <End>
inoremap <C-v> <PageDown>
"inoremap <A-v> <PageUp>
inoremap <C-\> <C-o>:left 0<CR><BS>
inoremap <C-_> <c-g>u<c-u>
inoremap <C-r> <c-g>u<C-o>u
inoremap <C-A-r> <c-g>u<c-o><c-r>$i
inoremap <c-u> <c-g>u<c-u>
inoremap <c-w> <c-g>u<c-w>

" Fix that 'Backspace' key does not work on Windows console.
if Mysys() != 'win32'
    inoremap <C-h> <Left>
endif

inoremap <C-l> <Right>
inoremap <C-f> <Right>
inoremap <C-b> <Left>

"Close other windows but current
nnoremap <leader>1 :only<CR>

"Close current window
nnoremap <leader>0 :close<CR>

"Repeat the last command
nnoremap <leader>. @:<CR>

"Active Django Mode
"nmap <leader>dj :call DjangoMode()<CR>

"Close the current buffer
"map <leader>bd :Bclose<cr>

"Close all the buffers
"map <leader>ba :1,1000 bd!<cr>

"Reload vimrc
nmap <leader>feR :so $MYVIMRC<CR>

"Toggle line number
nmap <silent> <leader>Tn :set nonumber!<CR>

"Toggle quickfix
nmap <silent> <leader>Tq :call ToggleList("Quickfix List", 'c')<CR>

"Useful mappings for managing tabs
nmap <silent> <leader>tb :tabnew<CR>
nmap <silent> <leader>tc :tabc<CR>
nmap <silent> <leader>tn :tabn<CR>
nmap <silent> <leader>tp :tabp<CR>
nmap <silent> <leader>ta :tabs<CR>
nmap <silent> <leader>to :tabo<CR>
nmap <silent> <leader>tf :tabfirst<CR>
nmap <silent> <leader>tl :tablast<CR>

"Useful mappings for buffers
nnoremap <silent> <leader>nb :nb<CR>
nnoremap <silent> <leader>np :np<CR>

"Maps for cmus
if !has('gui_running') && Mysys() == 'unix'
    nnoremap <silent> pc :r !cmus-remote --pause<cr>
    nnoremap <silent> pz :r !cmus-remote --prev<cr>
    nnoremap <silent> pb :r !cmus-remote --next<cr>
endif
"}

"transfer markdown to HTML
nnoremap md :!~/.vim/utils/markdown.pl % > %.html <CR><CR>

"transfer the tab to the space
nnoremap tt :%s/\t/    /g<CR>

nnoremap <silent> <leader>fex :Ex<cr>
nnoremap <silent> <leader>wj  :only<CR>
nnoremap <silent> <leader>py  :!python %<CR>
"nnoremap <silent> <leader><leader>  :BufExplorer<CR>
nnoremap <silent> <leader> :<c-u>LeaderGuide '<Space>'<CR>

set pastetoggle=<leader><F10>

"vimdiff{
nnoremap <silent> <leader>2 :diffget 2<CR> :diffupdate<CR>
nnoremap <silent> <leader>3 :diffget 3<CR> :diffupdate<CR>
nnoremap <silent> <leader>4 :diffget 4<CR> :diffupdate<CR>
"}

"python{
"au FileType python nmap ...
"}
"}

" disable auto-setting the help language to Chinese
let g:loaded_vimcdoc = 1

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" TIPS                                                                      "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 1. Diff two files in vim
"  When you have two files opened in vertical splitt, run  [:windo diffthis]
"
